using System.Collections;
using System.Collections.Generic;
using Player;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UIElements;

public class Spring : MonoBehaviour
{    
    [SerializeField] Vector2 direction;
    [SerializeField] float force;    
    [SerializeField] LayerMask targetLayer;    
    Animator animator;
    AudioSource audioSource;
    bool isLaunch = false;

    private void Start()
    {
        animator = GetComponent<Animator>();        
        audioSource = GetComponent<AudioSource>();
    }

    public float audioVolume;

    public void Launch()
    {
        animator.SetTrigger("Launch");
        audioSource.volume = audioVolume;
        audioSource.Play();
    }        

    void StartLaunch()
    {
        isLaunch = true;
    }

    //IEnumerator LaunchRoutine()
    //{
    //    while (isLaunch)
    //    {
    //        for(float i=180-raycastAngle;i<=raycastAngle;i+=10)
    //        {
    //            Vector2 dir = Quaternion.Euler(0,0,raycastAngle) * Vector2.right;
    //            RaycastHit2D raycastHit2D = Physics2D.Raycast(transform.position,dir,raycastDis,targetLayer);
    //            Debug.DrawRay(transform.position, dir, Color.black,5);
    //            if(raycastHit2D.collider!=null)
    //            {
    //                raycastHit2D.rigidbody.velocity = force * direction;
    //                isLaunch = false;
    //            }
    //        }
    //        yield return null;
    //    }
    //    yield break;
    //}

    //private void OnCollisionStay2D(Collision2D collision)
    //{       
    //    if(isLaunch && collision.gameObject.TryGetComponent<Rigidbody2D>(out var rb))
    //    {            
    //        rb.velocity = force * direction;
    //    }
    //}

    private void OnTriggerStay2D(Collider2D collision)
    {
        if (isLaunch && (1<<collision.gameObject.layer & targetLayer)!=0)
        {
            collision.gameObject.TryGetComponent<Rigidbody2D>(out var rb);
            PlayerController.canMove = false;
            rb.velocity = force * direction;
        }
    }

    void OnLaunchFinished()
    {
        isLaunch = false;        
    }    
}
